﻿using OpenTK.Graphics.OpenGL4;

namespace TrinityEngine
{
    public class VertexArray : IDisposable
    {
        private bool _disposed = false;

        private int _rendererID;

        public VertexArray()
        {
            _rendererID = GL.GenVertexArray();
            GL.BindVertexArray(_rendererID);
        }

        ~VertexArray()
        {
            Dispose(false);
        }

        public void AddBuffer(VertexBufferLayout layout)
        {
            Bind();
            var elements = layout.GetElements();
            int offset = 0;
            for (int i = 0; i < elements.Count; i++)
            {
                var element = elements[i];
                GL.EnableVertexAttribArray(i);
                GL.VertexAttribPointer(i, element.count, element.type, element.normalized, layout.GetStride(), offset);
                offset += element.count * VertexBufferElement.GetSizeOfType(element.type);
            }
        }

        public void Bind()
        {
            GL.BindVertexArray(_rendererID);
        }

        public void Unbind()
        {
            GL.BindVertexArray(0);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {

            }

            GL.DeleteVertexArray(_rendererID);

            _disposed = true;
        }
    }
}
